#ifndef VERTEX_BUFFER_H
#define VERTEX_BUFFER_H

#include "EngineApi.h"
#include "Struct.h"

template <class PixelFormatClass, UINT FVF>
class ENGINE_API VertexBuffer
{
public:
   VertexBuffer() : m_pVertexBuffer(NULL), m_pDxDevice(NULL), m_bufferSize(0) {}
   
   bool create(LPDIRECT3DDEVICE9 pDxDevice, UINT bufferSize = 400)
   {
      m_pDxDevice = pDxDevice;
      m_bufferSize = bufferSize;

      HRESULT hr = m_pDxDevice->CreateVertexBuffer(
         m_bufferSize * sizeof(PixelFormatClass),
         D3DUSAGE_WRITEONLY,
         FVF,
         D3DPOOL_MANAGED,
         &m_pVertexBuffer,
         NULL);

      if (hr != D3D_OK)
      {
         return false;
      }

      return true;
   }
   
   void bind()
   {
      m_pDxDevice->SetFVF(FVF);
      m_pDxDevice->SetStreamSource(0, m_pVertexBuffer, 0, sizeof(PixelFormatClass));
   }
   
   bool draw( PixelFormatClass* pVertexColection, USHORT vertexCount, USHORT primitiveCount, PRIM_TYPE primType )
   {
      void* pVertices;

      HRESULT hr = m_pVertexBuffer->Lock(
         0,
         m_bufferSize * sizeof(PixelFormatClass),
         &pVertices,0);

      if (hr != D3D_OK)
      {
         return false;
      }

      memcpy(pVertices, pVertexColection, sizeof(PixelFormatClass) * vertexCount); 
      
      hr = m_pVertexBuffer->Unlock();  

      if (hr != D3D_OK)
      {
         return false;
      }


      m_pDxDevice->DrawPrimitive( static_cast<D3DPRIMITIVETYPE>(primType), 0, primitiveCount);

      return true;
   }

private:
   LPDIRECT3DVERTEXBUFFER9 m_pVertexBuffer;
   LPDIRECT3DDEVICE9 m_pDxDevice;
   UINT m_bufferSize;
};

#endif//VERTEX_BUFFER_H